﻿using Newtonsoft.Json;
using System.Text;
using System.Text.RegularExpressions;

namespace Kz.Telegram.Bot.Infrastructure.Extensions
{
    public static class StringExtension
    {
        public static bool IsNullOrEmpty(this string str)
        {
            return string.IsNullOrEmpty(str);
        }

        public static int ToInt(this string str)
        {
            int.TryParse(str, out var result);
            return result;
        }

		public static bool StrIsNullOrWhiteSpace(this string str)
		{
            try
            {
				return string.IsNullOrWhiteSpace(str);
			}
			catch (System.Exception)
            {
                return true;
            }
		}

		public static T ToObject<T>(this string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 验证手机号码
        /// </summary>
        /// <param name="mobile"></param>
        /// <returns></returns>
        public static bool IsMobile(this string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
                return false;

            return Regex.IsMatch(mobile, @"^(1)\d{10}$");
        }


        /// <summary>
        /// 手机号脱敏
        /// </summary>
        /// <param name="phoneNo"></param>
        /// <returns></returns>
        public static string PhonedNumberDesensitization(this string phoneNo)
        {
            if (string.IsNullOrEmpty(phoneNo))
                return phoneNo;
            if (phoneNo.Length < 11)
            {
                return phoneNo;
            }
            StringBuilder sb = new StringBuilder(phoneNo.Substring(0, 3));
            for (int i = 0; i < phoneNo.Length - 7; i++)
            {
                sb.Append('*');
            }
            sb.Append(phoneNo.Substring(phoneNo.Length - 4));
            return sb.ToString();
        }

        /// <summary>
        /// 手机号脱敏 + 中间加4个****
        /// </summary>
        /// <param name="phoneNo"></param>
        /// <returns></returns>
        public static string PhonedNumberFourDesensitization(this string phoneNo)
        {
            if (string.IsNullOrEmpty(phoneNo))
                return phoneNo;
            if (phoneNo.Length < 11)
            {
                return phoneNo;
            }
            StringBuilder sb = new StringBuilder(phoneNo.Substring(0, 3));
            for (int i = 0; i < 4; i++)
            {
                sb.Append('*');
            }
            sb.Append(phoneNo.Substring(phoneNo.Length - 4));
            return sb.ToString();
        }
    }
}
